package main.com.votes.controller;

import main.com.votes.dao.UserDao;
import main.com.votes.model.User;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/AjaxRegisterServlet")
public class AjaxRegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    UserDao userDao = new UserDao();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        boolean userExists = checkUserExists(username);

        response.setContentType("text/html;charset=UTF-8");
        if (userExists) {
            response.getWriter().write("用户名已存在");
        } else {
            response.getWriter().write("用户名可以使用");
        }
    }

    private boolean checkUserExists(String username) {
        User user = userDao.getUserByUsername(username);
        if (user != null) {
            return true;
        } else {
            return false;
        }
    }
}
